package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"backend/Service/minioService"
	"backend/config"
	"backend/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"net/url"
	"strings"
)

type DataSpaceController struct {
}

//
// PutFile
// @Description: 上传文件到资源库
// @author MaTaoXun 2022-01-15 17:01:06
// @return gin.HandlerFunc
//
func (this DataSpaceController) PutFile(c *gin.Context) {
	// 单文件
	file, _ := c.FormFile("file")
	log.Println(file.Filename)
	open, _ := file.Open()
	err, m := minioService.UploadFile("dataspace", file.Filename, "dad/", open)
	if err != nil {
		fmt.Println("UploadHomeWorkerr", err)
	}
	fmt.Println(m)
	d := &Dao.DataSpace{
		Model:    Dao.GetModel(),
		DataName: file.Filename,
		DataUrl:  m.Key,
	}
	dbService.DbConn.Create(d)
	c.JSON(http.StatusOK, *d)
}

type reqGetFileList struct {
	IdList string
}

//
// GetFileList
// @Description: 根据资源库中资源id的列表,获取资源库的列表
// @author MaTaoXun 2022-01-15 17:01:32
// @return gin.HandlerFunc
//
func (this DataSpaceController) GetFileList(c *gin.Context) {
	data := reqGetFileList{}
	c.BindJSON(&data)
	var spaces []Dao.DataSpace
	dbService.DbConn.Find(&spaces, strings.Split(data.IdList, ","))
	c.JSON(200, spaces)
}

//
// GetAllFileList
// @Description: 获取所有的资源库中的资源列表
// @author MaTaoXun 2022-01-15 17:02:20
// @return gin.HandlerFunc
//
func (this DataSpaceController) GetAllFileList(c *gin.Context) {

	spaces := []Dao.DataSpace{}
	dbService.DbConn.Find(&spaces)
	c.JSON(200, spaces)
}

//
// GetDataSpaceFileByUrl
// @Description: 下载资源库文件(通过代理minio达成效果)
// @author MaTaoXun 2022-01-15 17:03:05
// @return gin.HandlerFunc
//
func (this DataSpaceController) GetDataSpaceFileByUrl(c *gin.Context) {

	ure := c.Query("url")
	//file, _ := minioService.GetFile(url, "homework")
	//c.Header("Content-Length", strconv.Itoa(len(file)))
	//c.Header("Content-Disposition", "attachment;")
	//c.Header("Content-Transfer-Encoding", "binary")
	//c.Data(http.StatusOK, "application/octet-stream", file)
	proxyUrl, _ := url.Parse("http://" + config.Config.Minio.Endpoint + "/dataspace/" + ure)
	fmt.Println(ure)

	proxy := util.GetPorxy(proxyUrl)
	c.Request.URL.Path = ""
	fmt.Println(c.Request.URL)
	proxy.ServeHTTP(c.Writer, c.Request)

	c.Abort()
}
